import { lazyReportCache } from '../utils/report.js'
import { onCachePageshow, getPagePath, isSupportPerformanceObserver } from '../utils/common.js'

let lcpDone = false
export function isLCPDone() {
    return lcpDone
}
/**
 * 最大文本块或图像元素在屏幕上完成渲染的时间
 * */
export default function observeLCP() {
    if (!isSupportPerformanceObserver()) {
        lcpDone = true
        return
    }
    
    const entryHandler = (list) => {
        lcpDone = true

        if (observer) {
            observer.disconnect()
        }
        
        for (const entry of list.getEntries()) {
            const json = entry.toJSON()
            Reflect.deleteProperty(json, 'duration')
            const data = {
                ...json,
                type: 'performance',
                subType: entry.entryType,
                pagePath: getPagePath(),
                target: entry.element?.tagName.toLowerCase(),
                name: entry.entryType,
            }
            lazyReportCache(data)
        }
    }

    const observer = new PerformanceObserver(entryHandler)
    observer.observe({ type: 'largest-contentful-paint', buffered: true })
    onCachePageshow(event => {
        requestAnimationFrame(() => {
            const data = {
                startTime: performance.now() - event.timeStamp,
                name: 'largest-contentful-paint',
                subType: 'largest-contentful-paint',
                type: 'performance',
                pagePath: getPagePath(),
                bfc: true,
            }
            lazyReportCache(data)
        })
    })
}
